package com.donleo.student.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donleo.common.api.CommonResult;
import com.donleo.common.model.Team;
import com.donleo.common.relation.TeamChangeRecord;
import com.donleo.common.relation.UserTeamRelation;
import com.donleo.common.utils.CommonPath;
import com.donleo.student.mapper.TeamChangeRecordMapper;
import com.donleo.student.mapper.TeamMapper;
import com.donleo.student.mapper.UserTeamRelationMapper;
import com.donleo.student.service.TeamService;
import com.donleo.student.service.UserService;
import com.donleo.student.vo.TeamVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 小组表 服务实现类
 * </p>
 *
 * @author liangd
 * @since 2020-12-21
 */
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private UserTeamRelationMapper userTeamRelationMapper;

    @Autowired
    private TeamChangeRecordMapper teamChangeRecordMapper;

    @Override
    public CommonResult add(Team team) {
        try {
            CommonResult result1 = userService.findByCode(team.getCoach());
            String username1 = (String) result1.getData();
            CommonResult result2 = userService.findByCode(team.getHeadMaster());
            String username2 = (String) result2.getData();
            team.setCoach(username1);
            team.setHeadMaster(username2);
            team.setDataEnable(CommonPath.YES.getValue());
            team.setCreateTime(new Date());
            int count = teamMapper.insert(team);
            if (count > 0) {
                return CommonResult.success(count);
            }
        } catch (Exception e) {
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult delete(Integer id) {
        Team team = teamMapper.selectById(id);
        List<UserTeamRelation> list = new LambdaQueryChainWrapper<>(userTeamRelationMapper)
                .eq(UserTeamRelation::getTeamCode, team.getCode())
                .list();
        //如果小组已经分配的成员，则不能删除
        if (list.size() > 0) {
            return CommonResult.failed();
        }
        return CommonResult.success(list);
    }

    @Override
    public CommonResult updateTeam(Team team) {
        team.setUpdateTime(new Date());
        int count = teamMapper.updateById(team);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @Override
    public Team findById(Integer id) {
        return teamMapper.selectById(id);
    }

    @Override
    public List<Team> findAll(TeamVo teamVo) {
        List<Team> list = teamMapper.findAll(teamVo);
        List<Team> collect = list.stream().map(team -> {
            Team t = new Team();
            t.setId(team.getId());
            t.setLeader(team.getLeader());
            t.setHeadMaster(team.getHeadMaster());
            t.setCoach(team.getCoach());
            t.setUpdateTime(team.getUpdateTime());
            t.setCreateTime(team.getCreateTime());
            t.setDataEnable(team.getDataEnable());
            t.setCode(team.getCode());
            t.setName(team.getName());
            t.setNumber(teamMapper.getTeamMumberCount(team.getCode()));
            return t;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public long getCount(TeamVo teamVo) {
        return teamMapper.getCount(teamVo);
    }

    @Override
    public CommonResult distributeLeader(Team team) {

        Team teamOne = teamMapper.selectById(team.getId());
        UserTeamRelation userTeamRelation = new UserTeamRelation();
        userTeamRelation.setTeamCode(teamOne.getCode());
        userTeamRelation.setUserCode(team.getLeader());
        //判断是更新操作还是插入操作
        List<UserTeamRelation> list = new LambdaQueryChainWrapper<>(userTeamRelationMapper)
                .eq(UserTeamRelation::getUserCode, team.getLeader())
                .list();
        if (list.size() > 0) {
            userTeamRelation.setId(list.get(0).getId());
            userTeamRelationMapper.updateById(userTeamRelation);
        } else {
            userTeamRelationMapper.insert(userTeamRelation);
        }
        //小组更新,设置小组长用户名字
        CommonResult byCode = userService.findByCode(team.getLeader());
        String username = (String) byCode.getData();
        team.setLeader(username);
        int i = teamMapper.updateById(team);
        if (i > 0) {
            return CommonResult.success(i);
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult distributeMembers(String teamCode, List<String> strings) {
        try {
            /************************  换组记录 ****************************/
            //查询当前小组
            Team team = new LambdaQueryChainWrapper<>(teamMapper).eq(Team::getCode, teamCode).one();
            //查询分组成员之前是否在其它组
            List<UserTeamRelation> utrList = userTeamRelationMapper.selectByUserCodes(strings);
            if (utrList.size() > 0) {
                for (UserTeamRelation utr : utrList) {
                    //如果小组编号不相等，删除
                    if (!utr.getTeamCode().equals(teamCode)) {
                        //查询之前小组
                        Team team1 = new LambdaQueryChainWrapper<>(teamMapper).eq(Team::getCode, utr.getTeamCode()).one();
                        TeamChangeRecord teamChangeRecord = new TeamChangeRecord();
                        teamChangeRecord.setUserCode(utr.getUserCode());
                        teamChangeRecord.setPastTeam(team1.getName());
                        teamChangeRecord.setCurrentTeam(team.getName());
                        teamChangeRecord.setChangeTime(new Date());
                        //插入换组记录
                        teamChangeRecordMapper.insert(teamChangeRecord);
                        //从这个小组中删除该用户
                        userTeamRelationMapper.deleteByUserCode(utr.getUserCode());
                    }
                }
            }

            /*****************分配组员********************/
            //查询该小组之前拥有的成员
            List<UserTeamRelation> list = new LambdaQueryChainWrapper<>(userTeamRelationMapper)
                    .eq(UserTeamRelation::getTeamCode, teamCode)
                    .list();
            //获取成员编号
            List<String> collect = list.stream()
                    .map(UserTeamRelation::getUserCode)
                    .collect(Collectors.toList());
            //colect集合中有而strings集合中没有的
            Collection c1 = CollectionUtils.subtract(collect, strings);
            List<String> s1 = new ArrayList<>(c1);
            int count = 0;
            if (s1.size() != 0) {
                userTeamRelationMapper.deleteByTeamCodeAndUserCodes(teamCode, s1);
            }
            //strings集合中有而collect集合中没有的
            Collection c2 = CollectionUtils.subtract(strings, collect);
            List<String> s2 = new ArrayList<>(c2);
            List<UserTeamRelation> utList = new ArrayList<>();
            for (String str : s2) {
                UserTeamRelation userTeamRelation = new UserTeamRelation();
                userTeamRelation.setTeamCode(teamCode);
                userTeamRelation.setUserCode(str);
                utList.add(userTeamRelation);
            }
            if (utList.size() != 0) {
                count = userTeamRelationMapper.insertBatch(utList);
            }
            if (count > 0) {
                return CommonResult.success(count);
            }
            return CommonResult.success(count);
        } catch (Exception e) {
            return CommonResult.failed();
        }

    }
}
